package com.dh.blog.controllers;

import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dh.blog.auth.AuthUtils;
import com.dh.blog.service.BlogService;
import com.dh.blog.service.VisitorService;
import com.dh.blog.vo.BlogVo;
import com.dh.blog.vo.CountVo;
import com.dh.blog.vo.LeaveVo;
import com.dh.blog.vo.NewsPagerVo;
import com.dh.blog.vo.PagerVo;
import com.dh.blog.vo.VisitorVo;
import com.ewei.web.common.json.resolver.JsonModel;
import com.ewei.web.common.response.ResponseVO;
import com.ewei.web.common.validator.SaveGroup;

/**
 * 博客控制器
 * 发起请求时有时候为了唯一标识博客，url要带有博客标识符，所以采用两种方式，
 * 一种是路径path，一种是id，分别对应url是/{blog_path},/{blog_id}
 * path用于站外页面定位，作uri前缀；id用于站内数据定位，作uri后缀
 * 如果没有前后缀，既为"/"，则为配置文件中默认的博客path
 * @author David
 *
 */
@RequestMapping("/")
@Controller
public class BlogController {
//	private static final Logger logger = LogManager.getLogger(BlogController.class);
	@Resource
	private Properties config;
	@Resource(name="blogService")
	private BlogService blogService;
	@Resource(name="visitorService")
	private VisitorService visitorService;
	@RequestMapping(value = "/",method=RequestMethod.GET)
	public ModelAndView index(){
		return index(config.getProperty("blogger_path"));
	}
	/**
	 * 根据路径访问博客
	 * @param path
	 */
	@RequestMapping(value ="/{blog_path:\\w+}",method=RequestMethod.GET)
	public ModelAndView index(@PathVariable("blog_path")String path){
		BlogVo blog = blogService.doVisitBlog(path);
		ModelAndView model = new ModelAndView("iblog");
		model.addObject("blog", blog);
		return model;
	}
	/**
	 * 页面跳转
	 * @param path
	 * @param page
	 */
	@RequestMapping(value ="/{blog_path:^(?!admin)\\w*}/{page_index:article|daily|photos|collection}/**",
			method=RequestMethod.GET)
	public ModelAndView webPage(@PathVariable("blog_path")String path,
			@PathVariable("page_index")String page,HttpServletRequest request){
		BlogVo blog = blogService.browse(path);
		String uri = request.getRequestURI();
		uri = uri.substring(uri.indexOf(page)-1);
		String forward = "forward:"+uri+"/"+blog.getId();//转发到对应控制器进行数据处理,尾部添加博客id
		ModelAndView model = new ModelAndView(forward);
		model.addObject("blog", blog);
		return model;
	}
	/**
	 * 计数器
	 * @param blogId
	 * @return
	 */
	@RequestMapping(value="/counter/{blog_id:\\w+}",method=RequestMethod.GET)
	@ResponseBody
	public Object counter(@PathVariable("blog_id")String blogId){
		CountVo countVo = blogService.getCounts(blogId);
		return new ResponseVO().setDatas(countVo);
	}
	/**
	 * 系统动态信息
	 * @return
	 */
	@RequestMapping(value="/sysnews/{blog_id:\\w+}",method=RequestMethod.GET)
	@ResponseBody
	public Object systemNews(@PathVariable("blog_id")String blogId,
			@JsonModel NewsPagerVo newsPager){
		newsPager.setBlogId(blogId);
		PagerVo pager = blogService.findNewsByPager(newsPager);
		return new ResponseVO().setDatas(pager);
	}
	/**
	 * 博客留言
	 * TODO (暂时写在Blog主Controller里，后期考虑是否分出去）
	 */
	@RequestMapping(value="/leave",method=RequestMethod.POST)
	@ResponseBody
	public Object leave(@JsonModel @Validated({SaveGroup.class})LeaveVo leaveVo,BindingResult result){
		if(result.hasErrors()){
			return new ResponseVO().resolveError(result);
		}
		String identify = AuthUtils.getIdentify();
		if(null != identify && !"".equals(identify.trim())){
			VisitorVo visitor = visitorService.getVisitorById(identify);//将身份信息作为id来查找游客信息
			if(null != visitor){
				leaveVo.setVisitor(visitor);
			}
		}
		leaveVo.setCreateTime(Calendar.getInstance().getTime());
		blogService.doSaveleaveWord(leaveVo);
		return new ResponseVO();
	}
	/**
	 * 博客留言列表
	 * @return
	 */
	@RequestMapping(value="/leave/list/{blog_id:\\w+}",method=RequestMethod.GET)
	@ResponseBody
	public Object leaveList(@PathVariable("blog_id")String blogId){
		System.out.println(blogId);
		List<LeaveVo> list = blogService.getTopLeaveWords(blogId); 
		return new ResponseVO().setDatas(list);
	}
}
